package com.wwwarehouse.resource_center.customView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Joseph on 2017/9/18.
 *         <p/>
 */

public class FilterEdittext extends EditText {

    public FilterEdittext(Context context) {
        super(context);
    }

    public FilterEdittext(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FilterEdittext(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new MyInputConnecttion(super.onCreateInputConnection(outAttrs),
                false);
    }


    class MyInputConnecttion extends InputConnectionWrapper implements InputConnection {

        public MyInputConnecttion(InputConnection target, boolean mutable) {
            super(target, mutable);
        }


        @Override
        public boolean commitText(CharSequence text, int newCursorPosition) {
            if (!Pattern.compile("^[a-zA-Z0-9\u4E00-\u9FA5]+$").matcher(text.toString()).matches()) {
                return false;
            }
            return super.commitText(text, newCursorPosition);
        }
    }

}
